package com.dragon.framework.context;

import com.alibaba.ttl.TransmittableThreadLocal;
import com.dragon.common.constant.BasicConstant;
import com.dragon.common.core.text.Convert;
import org.apache.commons.lang3.StringUtils;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 安全上下文持有者
 * 获取当前线程变量中的信息
 * 注意： 必须在网关通过请求头的方法传入，同时在HeaderInterceptor拦截器设置值。 否则这里无法获取
 *
 * @author dragon
 * @version 1.0
 * @date 2024/7/30 16:04
 */
public class SecurityContextHolder {

    private static final TransmittableThreadLocal<Map<String, Object>> THREAD_LOCAL = new TransmittableThreadLocal<>();

    public static void set(String key, Object value) {
        Map<String, Object> map = getLocalMap();
        map.put(key, value == null ? StringUtils.EMPTY : value);
    }

    public static void remove(String key) {
        Map<String, Object> map = getLocalMap();
        map.remove(key);
    }

    public static void remove() {
        THREAD_LOCAL.remove();
    }

    public static String get(String key) {
        Map<String, Object> map = getLocalMap();
        return Convert.toStr(map.getOrDefault(key, StringUtils.EMPTY));
    }

    public static <T> T get(String key, Class<T> clazz) {
        Map<String, Object> map = getLocalMap();
        return clazz.cast(map.getOrDefault(key, null));
    }

    public static Map<String, Object> getLocalMap() {
        Map<String, Object> map = THREAD_LOCAL.get();
        if (map == null) {
            map = new ConcurrentHashMap<String, Object>(16);
            THREAD_LOCAL.set(map);
        }
        return map;
    }


    public static void setLocalMap(Map<String, Object> threadLocalMap) {
        THREAD_LOCAL.set(threadLocalMap);
    }

    /**
     * 获取全局追踪ID
     *
     * @return 追踪ID
     */
    public static String getTraceId() {
        return get(BasicConstant.TRACE_ID);
    }

    /**
     * 设置全局追踪ID
     *
     * @param traceId 追踪ID
     */
    public static void setTraceId(String traceId) {
        set(BasicConstant.TRACE_ID, traceId);
    }

    /**
     * 设置登陆用户ID
     * @param userId 用户ID
     */
    public static void setUserId(Long userId) {
        set(BasicConstant.USER_ID, userId);
    }

    /**
     * 获取登陆用户ID
     * @return 用户ID
     */
    public static Long getUserId() {
        return get(BasicConstant.USER_ID, Long.class);
    }

}
